package com.portal.test;

import io.jsonwebtoken.*;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class AppJwt {
    String secret = "qwertyuiodfgjklcvbnm.fghjk";
    @Test
    public void createToken() {
        JwtBuilder builder = Jwts.builder();
        //1、头部
        builder.setHeaderParam("typ", "JWT");
        builder.setHeaderParam("alg", "HS256");

        //2、载荷 Payload
        builder.claim("userId","1000");
        builder.claim("username","Jack");

        //3、设置签名
        builder.signWith(SignatureAlgorithm.HS256,secret);

        //4、生成token
        String token = builder.compact();
        System.out.println("token = " + token);
    }


    //解析Token
    // http协议规范，前段请求后台传递token是在请求头中，格式：
    // Authorizaiton "Bearer eycjjjjjxxxx..."
    @Test
    public void testParsingToken() {
        //得到token
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiIxMDAwIiwidXNlcm5hbWUiOiJKYWNrIn0.tngv7iA75KQ9H1fEsqRlPAby8ipear_f_lITBv10GUM";
        //1.创建JwtParser对象
        JwtParser parser = Jwts.parser();
        //2.设置签名的秘钥
        parser.setSigningKey("aasd");
        //3.解析Token
        Jws<Claims> claimsJws = parser.parseClaimsJws(token);
        //4.得到载荷
        Claims claims = claimsJws.getBody();
        //5.从载荷中获取数据
        System.out.println("userId：" + claims.get("userId"));
        System.out.println("username：" + claims.get("username"));
    }
}
